"""
Hinge损失
"""
import numpy as np
from keras.losses import Hinge, hinge


def get_data():
    """

    :return:
    """
    y_true = [[0.0, 1.0], [0.0, 0.0]]
    y_pred = [[0.6, 0.4], [0.4, 0.6]]
    return np.array(y_true), np.array(y_pred)


def compute_hinge(y_true, y_pred):
    """

    :param y_true:
    :param y_pred:
    :return:
    """
    # 将true中的0置换为-1
    y_true[y_true == 0] = -1
    loss = np.maximum(1 - y_true * y_pred, 0)

    return loss.mean(axis=1), loss.mean()


def run():
    """
    主程序
    :return:
    """
    y_true, y_pred = get_data()

    # 自己计算
    hinge_func, hinge_class = compute_hinge(y_true=y_true, y_pred=y_pred)

    loss_class = Hinge()

    info = 'Class: my hinge: {}; hinge: {}\nFunction: my hinge: {}, hinge: {}'.\
        format(hinge_class, loss_class(y_true=y_true, y_pred=y_pred),
               hinge_func, hinge(y_true=y_true, y_pred=y_pred))
    print(info)


if __name__ == '__main__':
    run()
